import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import * as APP_CONFIG from '@app/app.config';
import { lastValueFrom } from 'rxjs';

@Injectable()
export class MapService {
  private readonly baseUrl = 'https://mcp.amap.com/mcp';
  private readonly apiKey: string;

  constructor(
    private readonly httpService: HttpService,
  ) {
    this.apiKey = APP_CONFIG.AMAP.KEY;
  }

  async callTool(toolName: string, parameters: Record<string, any>): Promise<any> {
    const requestUrl = `${this.baseUrl}?key=${this.apiKey}`;

    const requestBody = {
      tool: toolName,
      params: parameters,
    };

    try {
      const response = await lastValueFrom(
        this.httpService.post(requestUrl, requestBody, {
          headers: { 'Content-Type': 'application/json' },
        })
      );
      console.log('高德MCP工具调用成功:', response.data);
      return response.data;
    } catch (error) {
      throw new Error(`调用高德MCP工具失败: ${error.message}`);
    }
  }

  // 封装具体的高德服务方法
  async searchPOI(keywords: string, city: string) {
    return this.callTool('maps_text_search', { keywords, city });
  }

  async geocode(address: string, city?: string) {
    const params = { address };
    if (city) params['city'] = city;
    return this.callTool('maps_geo', params);
  }

  async drivingRoute(origin: string, destination: string, waypoints?: string) {
    const params = { origin, destination };
    if (waypoints) params['waypoints'] = waypoints;
    return this.callTool('maps_direction_driving', params);
  }

  async getWeather(city: string) {
    return this.callTool('maps_weather', { city });
  }

  async aroundSearch(location: string, keywords: string, radius: number = 5000) {
    return this.callTool('maps_around_search', { location, keywords, radius });
  }
}
